import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_member/widget/balance_item.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:collection/collection.dart';
class BalancePage extends StatefulWidget {
  @override
  _BalancePageState createState() => _BalancePageState();
}

/*
 * 余额页面
 */
class _BalancePageState extends State<BalancePage> {

// 切換tab的標籤欄數據
  List<String>tabs=['紀錄','充值'];

  /// 先使用 list存储，在转换 map
  List <dynamic> listBalance= [];
  /// 第一次余额记录，转换年份
  Map mapData={};
  // 第二次余额记录，转换月份
  Map mapBalance={};
  // 一次加载5条数据
  int loadData = 5;
  // 加载中
  bool _loading =true;

  var _indexedStack = 0;

//  初始化数据
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getMemberBalance();
  }
  ///查询余额
  Future<void> getMemberBalance() async {
    final ParseUser user = await ParseUser.currentUser();
    var queryMemStaLog =
    QueryBuilder<ParseObject>(ParseObject('MemberStatisticsLog'))
      ..whereEqualTo("member", user.get("member"));
    queryMemStaLog.setLimit(loadData);
    var response = await queryMemStaLog.query();
    if (response.success && response.results != null) {
      mapData.clear();
      mapBalance.clear();
      listBalance.clear();
      setState(() {
        _loading=false;
        listBalance= response.results.map((e) => {
          "objectId" : e["objectId"],
          "remark" : e["remark"],
          "year" : formatDate(e["date"],[yyyy]),
          "month" : formatDate(e['date'], [mm]),
          "date" : e['date'],
          "value" : e["value"],
          "type" : e["type"],
          "createdAt" : e["createdAt"]
        }).toList();
        mapData = groupBy(listBalance,(obj)=>obj['year']);
        mapBalance=mapData.map((key, value) {
          return MapEntry(key,groupBy(value,(obj)=>obj['month']));
        });
      });
    }else{
      setState(()=>_loading=false);
    }
  }
  @override
  Widget build(BuildContext context) {
    TabController _tabController;
    ScreenUtil.init(context, designSize: Size(375, 667), allowFontScaling: false);
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: MyAppBar('餘額查詢'),
        body: IndexedStack(
          index: _indexedStack,
          alignment: Alignment.center,
          children: <Widget>[
            Column(
              children: <Widget>[
                TabBar(
                  isScrollable: true,
                  indicatorColor: Colors.yellow,
                  //指示器颜色
                  indicatorWeight: 5,
                  //指示器高度
                  indicatorPadding: EdgeInsets.fromLTRB(35, 0, 35, 0),
                  //底部指示器的Padding
                  labelColor: Color(0xff3d6fc1),
                  //选中label颜色
                  unselectedLabelColor: Color(0xffd9d9d9),
                  //未选中label颜色
                  labelStyle:
                  TextStyle(fontWeight: FontWeight.w500, fontSize: ScreenUtil().setSp(16)),
                  tabs: tabs
                      .map((f) => Tab(
                    child: Text(f),
                  ))
                      .toList(),
                  controller: _tabController,
                ),
                Expanded(
                  child: TabBarView(
                    children: <Widget>[
                      //紀錄
                      _bodyWidget(),
                      //充值
                      RechargePage()
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

//  顶部AppBar
  Widget MyAppBar(String title){
    return PreferredSize(
      child: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: 10, top: 10),
            width: double.infinity,
            height: ScreenUtil().setHeight(160),
            decoration: BoxDecoration(
                color: Color(0xffE5EEF6),
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25))),
          ),
          Container(
            padding: EdgeInsets.only(left: 10),
            width: double.infinity,
            height: ScreenUtil().setHeight(155),
            decoration: BoxDecoration(
                color: Color(0xff2D7FC7),
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25))),
            child: SafeArea(
                child: Stack(
                  children: <Widget>[
                    IconButton(
                      color: Color(0xffffffff),
                      icon: Icon(Icons.arrow_back),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      iconSize: 30,
                    ),
                   Container(
                     padding: EdgeInsets.only(top: 20),
                     width: MediaQuery.of(context).size.width,
                     child:  Column(

                       children: <Widget>[
                         Text(
                           title,
                           style: TextStyle(
                               color: Color(0xffffffff),
                               fontSize: ScreenUtil().setSp(15),
                               fontWeight: FontWeight.w500),
                           textAlign: TextAlign.center,
                         ),
                         Container(
                           padding: EdgeInsets.only(top: ScreenUtil().setHeight(15),left: ScreenUtil().setWidth(40)),
                           child: _balanceWidget(),
                         )
                       ],
                     ),
                   )
                  ],
                )),
          ),
        ],
      ),
      preferredSize: Size(double.infinity, 190),
    );
  }

  // 余额
  Widget _bodyWidget(){
    if(_loading==true){
      return CLoadingDialog(text: "加载中",);
    }else if(mapBalance.length!=0){
      return BalanceItem(
        mapDta: mapBalance,
        refresh: ()async{
          loadData=5;
          getMemberBalance();
        },
        load: ()async{
          loadData+=5;
          getMemberBalance();
        },
      );
    }else{
      return NoDataWidget();
    }
  }
//  顶部余额显示组件
  Widget _balanceWidget(){
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(bottomRight: Radius.circular(25),bottomLeft: Radius.circular(25))
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
         Container(
           child: Column(
             children: <Widget>[
               Text(
                 "\$768",
                 style: TextStyle(
                     color: Colors.white,
                     fontSize: ScreenUtil().setSp(52)
                 ),
               ),
             ],
           )
         ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('50',style: TextStyle(color: Colors.white,fontSize: ScreenUtil().setSp(32)),),
                Container(
                  padding: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                  child: Text(
                    '澳門幣 (MOP)',
                    style: TextStyle(color: Colors.white,fontSize: ScreenUtil().setSp(13)),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}


class RechargePage extends StatefulWidget {
  @override
  _RechargePageState createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  //選中支付狀態
  bool paymentBl = false;
  //充值頁面狀態
  int indexState = 0;
  List<Payment> _list = [
    Payment('信用卡', false, 'images/xyk.png'),
    Payment('銀聯信用卡', false, 'images/yl.png'),
    Payment('澳門通錢包', false, 'images/amt.png'),
    Payment('支付寶', false, 'images/zfb.png'),
    Payment('微信支付', false, 'images/wxzf.png'),
    Payment('線下支付', false, 'images/xxzf.png')
  ];

  //支付方式
  List<Widget> _getWidget() {
    return _list
        .map((payment) => GestureDetector(
      onTap: () {
        setState(() {
          for(var p in _list){
            p.bl = false;
          }
          payment.bl = true;
          //選中支付方式後按鈕狀態
          paymentBl = true;
        });
      },
      child: Card(
        shape:RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(15)),),
        elevation: 3,
        child: Container(
          width: ScreenUtil().setWidth(94),
          height: ScreenUtil().setHeight(70),
          decoration: payment.bl
              ? ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15)),
              shadows: [
                BoxShadow(
                    color: Colors.blue,
                    blurRadius: 15,
                    offset: Offset(0, 0))
              ])
              : ShapeDecoration(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15)),
          ),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius:BorderRadius.circular(15),//邊框
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 5),
                  width: ScreenUtil().setWidth(70),
                  height: ScreenUtil().setHeight(40),
                  child: payment.src != null
                      ? Image.asset(
                    payment.src,
                  )
                      : Image.asset(
                    'images/noimg.jpg',
                    fit: BoxFit.fill,
                  ),
                ),
                Container(
                  child: Text(
                    payment.title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: ScreenUtil().setSp(10),
                        color: Color(0Xff154D7C)),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    ))
        .toList();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(335),
      child: IndexedStack(
        index: indexState,
        alignment: Alignment.center,
        children: <Widget>[
          //充值方式
          Column(
            children: <Widget>[
              Container(
                width: ScreenUtil().setWidth(335),
                child: Text(
                  '充值方式',
                  style: TextStyle(
                    color: Color(0xff154D7C),
                    fontWeight: FontWeight.w500,
                    fontSize: ScreenUtil().setSp(12),
                    fontFamily:"SemiBold",
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                child: Wrap(
                  spacing: 5,
                  runAlignment: WrapAlignment.center,
                  runSpacing: 5,
                  children: _getWidget(),
                ),
              ),
              Container(
                margin:
                EdgeInsets.only(top: 30),
                width: ScreenUtil().setWidth(200),
                height: ScreenUtil().setHeight(50),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  //漸變色
                  gradient: LinearGradient(colors: [
                    Color(0xff93BB24),
                    Color(0xff2D7FC7)
                  ]),
                ),
                child: RaisedButton(
                  onPressed: !paymentBl?null:() {
                    setState(() {
                      indexState = 1;
                    });
                  },
                  child: Text(
                    '確認支付',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontFamily:"SemiBold",
                        fontSize: ScreenUtil().setSp(16)),
                  ),
                  textColor: Colors.white,
                  // 设为透明色
                  color: Colors.transparent,
                  disabledColor: Color(0Xff9fa3b9), //按鈕被禁用時候的顏色
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),
            ],
          ),
          //線下充值
          Column(
            children: <Widget>[
              Container(
                width: ScreenUtil().setWidth(335),
                child: Text(
                  '線下充值',
                  style: TextStyle(
                    color: Color(0xff154D7C),
                    fontWeight: FontWeight.w500,
                    fontSize: ScreenUtil().setSp(12),
                    fontFamily:"SemiBold",
                  ),
                ),
              ),
              Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: ScreenUtil().setWidth(137),
                        width: ScreenUtil().setWidth(137),
                        child: Image.asset('images/qrcode.png',fit: BoxFit.fill,),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 10,bottom: 10),
                        width: MediaQuery.of(context).size.width,
                        child: Text(
                          '* 請將二維碼顯示給職員進行線下支付程序',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Color(0Xff7b7b7b),
                              fontFamily:"SemiBold",
                              fontSize: ScreenUtil().setSp(12)
                          ),
                        ),
                      ),
                    ],
                  )
              ),
              Container(
                margin:
                EdgeInsets.only(top: 30),
                width: ScreenUtil().setWidth(200),
                height: ScreenUtil().setHeight(50),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  //漸變色
                  gradient: LinearGradient(colors: [
                    Color(0xff93BB24),
                    Color(0xff2D7FC7)
                  ]),
                ),
                child: RaisedButton(
                  onPressed: !paymentBl?null:() {
                    setState(() {
                      indexState = 1;
                    });
                  },
                  child: Text(
                    '確認支付',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontFamily:"SemiBold",
                        fontSize: ScreenUtil().setSp(16)),
                  ),
                  textColor: Colors.white,
                  // 设为透明色
                  color: Colors.transparent,
                  disabledColor: Color(0Xff9fa3b9), //按鈕被禁用時候的顏色
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class Payment {
  final String title;
  final String src;
  bool bl;
  Payment(this.title, this.bl, this.src);
}